package com.luo.divview2;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

/**
 * 自定义ImageView
 * <p>
 * Created by Luo on 2017/4/26 0026.
 */
public class CustomImageView extends View {
    // View的属性
    private String titleText = "";
    private int titleTextSize;
    private int titleTextColor;
    private Bitmap image;
    private int imageScaleType;

    // 画笔
    private Paint mPaint;
    // 文字区域
    private Rect mTextBound;
    // 内容区域
    private Rect rect;
    // View的宽高
    private int width;
    private int height;
    // 缩放类型
    private static final int IMAGE_SCALE_FITXY = 0;
    private static final int IMAGE_SCALE_CENTER = 1;

    public CustomImageView(Context context) {
        this(context, null);
    }

    public CustomImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 给image设置一个默认值
        image = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomImageView, defStyleAttr, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.CustomImageView_titleText:
                    titleText = a.getString(attr);
                    break;
                case R.styleable.CustomImageView_titleTextSize:
                    titleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                    break;
                case R.styleable.CustomImageView_titleTextColor:
                    titleTextColor = a.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.CustomImageView_image:
                    image = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0));
                    break;
                case R.styleable.CustomImageView_imageScaleType:
                    imageScaleType = a.getInt(attr, 0);
                    break;
            }
        }
        // 这个是从一个pool中拿到的，用完了记得回收
        a.recycle();
        // 创建一个画笔
        mPaint = new Paint();
        rect = new Rect();
        mTextBound = new Rect();
        mPaint.setTextSize(titleTextSize);
        // 计算了描绘字体需要的范围
        mPaint.getTextBounds(titleText, 0, titleText.length(), mTextBound);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /*
         * 设置宽度
         */
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        // 如果是一个确确的值
        if (specMode == MeasureSpec.EXACTLY) {
            width = specSize;
        } else {
            // 由图片决定的宽
            int desireByImg = getPaddingLeft() + getPaddingRight() + image.getWidth();
            // 由字体决定的宽
            int desireByTitle = getPaddingLeft() + getPaddingRight() + mTextBound.width();
            // wrap_content
            if (specMode == MeasureSpec.AT_MOST) {
                int desire = Math.max(desireByImg, desireByTitle);
                width = Math.min(desire, specSize);
            }
        }

        /*
         * 设置高度
         */
        specMode = MeasureSpec.getMode(heightMeasureSpec);
        specSize = MeasureSpec.getSize(heightMeasureSpec);
        // match_parent , accurate
        if (specMode == MeasureSpec.EXACTLY) {
            height = specSize;
        } else {
            int desire = getPaddingTop() + getPaddingBottom() + image.getHeight() + mTextBound.height();
            // wrap_content
            if (specMode == MeasureSpec.AT_MOST) {
                height = Math.min(desire, specSize);
            }
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setStrokeWidth(4);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.CYAN);
        // 画View的背景
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);
        // 这样就获取到了内容区域
        rect.left = getPaddingLeft();
        rect.right = width - getPaddingRight();
        rect.top = getPaddingTop();
        rect.bottom = height - getPaddingBottom();

        mPaint.setColor(titleTextColor);
        mPaint.setStyle(Paint.Style.FILL);

        /*
        文字的宽度大于控件的宽度
         */
        if (mTextBound.width() > width) {
            TextPaint textPaint = new TextPaint(mPaint);
            String msg = TextUtils.ellipsize(titleText, textPaint, (float) width - getPaddingLeft() - getPaddingRight(),
                    TextUtils.TruncateAt.END).toString();
            canvas.drawText(msg, getPaddingLeft(), height - getPaddingBottom(), mPaint);
        } else {
            // 正常情况
            canvas.drawText(titleText, width / 2 - mTextBound.width() * 1.0f / 2, height - getPaddingBottom(), mPaint);
        }

        // 取消使用过的块
        rect.bottom -= mTextBound.height();
        if (imageScaleType == IMAGE_SCALE_FITXY) {
            canvas.drawBitmap(image, null, rect, mPaint);
        } else {
            //计算居中的矩形范围
            rect.left = width / 2 - image.getWidth() / 2;
            rect.right = width / 2 + image.getWidth() / 2;
            rect.top = (height - mTextBound.height()) / 2 - image.getHeight() / 2;
            rect.bottom = (height - mTextBound.height()) / 2 + image.getHeight() / 2;

            canvas.drawBitmap(image, null, rect, mPaint);
        }
    }
}
